package com.mooc.ppjoke.ui.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.arch.core.executor.ArchTaskExecutor;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import com.alibaba.fastjson.JSONObject;
import com.mooc.lib_common.LiveDataBus;
import com.mooc.lib_common.MyApplication;
import com.mooc.lib_network.ApiResponse;
import com.mooc.lib_network.ApiService;
import com.mooc.lib_network.GetRequest;
import com.mooc.lib_network.JsonCallBack;
import com.mooc.ppjoke.data.Comment;
import com.mooc.ppjoke.data.Feed;
import com.mooc.ppjoke.data.TagList;
import com.mooc.ppjoke.data.User;
import com.mooc.ppjoke.ui.ShareDialog;
import com.mooc.ppjoke.ui.login.QQUserManager;


import java.util.Date;

/**
 * @ClassName: InteractionPresenter$
 * @Description: java类作用描述
 * @Author: 魏靳元
 * @CreateDate: 2022/8/21 19:54
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
public class InteractionPresenter {
    public static final String DATA_FROM_INTERACTION = "data_from_interaction";
    private static final String URL_TOGGLE_LIKE = "/ugc/toggleFeedLike";
    private static final String URL_TOGGLE_DISS = "/ugc/dissFeed";

    private static final String URL_SHARE = "/ugc/increaseShareCount";

    private static final String URL_TOGGLE_COMMENT_LIKE = "/ugc/toggleCommentLike";

    public static void toggleFeedLike(LifecycleOwner owner, Feed feed) {
        if (!QQUserManager.getInstance().isLogin()) {
            LiveData<User> loginLv = QQUserManager.getInstance().login(MyApplication.getsApplication());
            loginLv.observe(owner, new Observer<User>() {
                @Override
                public void onChanged(User user) {
                    if (user != null) {
                        toggleFeedLikeInternal(feed);
                    }
                    loginLv.removeObserver(this);
                }
            });
        }else {
            toggleFeedLikeInternal(feed);
        }
    }

    private static void toggleFeedLikeInternal(Feed feed) {
        GetRequest request = ApiService.get(URL_TOGGLE_LIKE);
        request.addParam("userId", QQUserManager.getInstance().getUserId());
        request.addParam("itemId", feed.itemId);
        request.excute(new JsonCallBack<JSONObject>() {
            @Override
            public void OnSuccess(ApiResponse<JSONObject> apiResponse)  {
                if (apiResponse.body != null) {
                    boolean hasLiked = apiResponse.body.getBoolean("hasLiked").booleanValue();

                    feed.getUgc().setHasLiked(hasLiked);
                    LiveDataBus.get().with(DATA_FROM_INTERACTION)
                            .postValue(feed);
                }
            }

            @Override
            public void OnError(ApiResponse<JSONObject> apiResponse) {
                showToast(apiResponse.message);
            }
        });
    }

    public static void toggleFeedDiss(LifecycleOwner owner, Feed feed) {
        if (!QQUserManager.getInstance().isLogin()) {
            LiveData<User> loginLv = QQUserManager.getInstance().login(MyApplication.getsApplication());
            loginLv.observe(owner,new Observer<User>() {
                @Override
                public void onChanged(User user) {
                    if (user != null) {
                        toggleFeedDissInternal(feed);
                    }
                    loginLv.removeObserver(this);
                }
            });
        }else {
            toggleFeedDissInternal(feed);
        }
    }

    private static void toggleFeedDissInternal(Feed feed) {
        GetRequest request = ApiService.get(URL_TOGGLE_DISS);
        request.addParam("userId", QQUserManager.getInstance().getUserId());
        request.addParam("itemId", feed.itemId);
        request.excute(new JsonCallBack<JSONObject>() {
            @Override
            public void OnSuccess(ApiResponse<JSONObject> apiResponse)  {
                if (apiResponse.body != null) {
                    boolean hasDiss = apiResponse.body.getBoolean("hasLiked").booleanValue();
                    feed.getUgc().setHasdiss(hasDiss);
                }
            }
        });
    }


    @SuppressLint("RestrictedApi")
    private static void showToast(String message) {
        ArchTaskExecutor.getMainThreadExecutor().execute(() -> Toast.makeText(MyApplication.getsApplication(), message, Toast.LENGTH_SHORT).show());
    }

    public static void openShare(Context context, Feed feed) {
        String url = "http://h5.aliyun.ppjoke.com/item/%s?timestamp=%s&user_id=%s";
        String format = String.format(url, feed.itemId, new Date().getTime(), QQUserManager.getInstance().getUserId());
        ShareDialog shareDialog = new ShareDialog(context);
        shareDialog.setShareContent(format);
        shareDialog.setShareItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ApiService.get(URL_SHARE)
                        .addParam("itemId", feed.itemId)
                        .excute(new JsonCallBack<JSONObject>() {
                            @Override
                            public void OnSuccess(ApiResponse<JSONObject> apiResponse)  {
                                if (apiResponse.body != null) {
                                    int count = apiResponse.body.getIntValue("count");
                                    feed.getUgc().setShareCount(count);
                                }
                            }
                        });
            }
        });
        shareDialog.show();

    }

    //给一个帖子的评论点赞/取消点赞
    public static void toggleCommentLike(LifecycleOwner owner, Comment comment) {
        if (!QQUserManager.getInstance().isLogin()) {
            LiveData<User> loginLv = QQUserManager.getInstance().login(MyApplication.getsApplication());
            loginLv.observe(owner, new Observer<User>() {
                @Override
                public void onChanged(User user) {
                    if (user != null) {
                        toggleCommentLikeInternal(comment);
                    }
                    loginLv.removeObserver(this);
                }
            });
        }else {
            toggleCommentLikeInternal(comment);
        }
    }

    private static void toggleCommentLikeInternal(Comment comment) {

        GetRequest request = ApiService.get(URL_TOGGLE_COMMENT_LIKE)
                .addParam("commentId", comment.commentId);
        request.addParam("userId", QQUserManager.getInstance().getUserId());
        request.excute(new JsonCallBack<JSONObject>() {
            @Override
            public void OnSuccess(ApiResponse<JSONObject> response)  {
                if (response.body != null) {
                    boolean hasLiked = response.body.getBoolean("hasLiked").booleanValue();
                    comment.getUgc().setHasLiked(hasLiked);
                }
            }

            @Override
            public void OnError(ApiResponse<JSONObject> response) {
                showToast(response.message);
            }
        });
    }
    public static void toggleFeedFavorite(LifecycleOwner owner, Feed feed) {
        if (!QQUserManager.getInstance().isLogin()) {
            LiveData<User> loginLv = QQUserManager.getInstance().login(MyApplication.getsApplication());
            loginLv.observe(owner, new Observer<User>() {
                @Override
                public void onChanged(User user) {
                    if (user != null) {
                        toggleFeedFavoriteInternal(feed);
                    }
                    loginLv.removeObserver(this);
                }
            });
        }else {
            toggleFeedFavoriteInternal(feed);
        }
    }

    private static void toggleFeedFavoriteInternal( Feed feed) {
        ApiService.get("/ugc/toggleFavorite")
                .addParam("itemId", feed.itemId)
                .addParam("userId", QQUserManager.getInstance().getUserId())
                .excute(new JsonCallBack<JSONObject>() {
                    @Override
                    public void OnSuccess(ApiResponse<JSONObject> response)  {
                        if (response.body != null) {
                            boolean hasFavorite = response.body.getBoolean("hasFavorite");
                            feed.getUgc().setHasFavorite(hasFavorite);
                            LiveDataBus.get().with(DATA_FROM_INTERACTION)
                                    .postValue(feed);
                        }
                    }

                    @Override
                    public void OnError(ApiResponse<JSONObject> response) {
                        showToast(response.message);
                    }
                });
    }
    //关注/取消关注一个用户
    public static void toggleFollowUser(LifecycleOwner owner, Feed feed) {
        if (!QQUserManager.getInstance().isLogin()) {
            LiveData<User> loginLv = QQUserManager.getInstance().login(MyApplication.getsApplication());
            loginLv.observe(owner, new Observer<User>() {
                @Override
                public void onChanged(User user) {
                    if (user != null) {
                        toggleFollowUserInternal(feed);
                    }
                    loginLv.removeObserver(this);
                }
            });
        }else {
            toggleFollowUserInternal(feed);
        }
    }

    private static void toggleFollowUserInternal(Feed feed) {
        ApiService.get("/ugc/toggleUserFollow")
                .addParam("followUserId", QQUserManager.getInstance().getUserId())
                .addParam("userId", feed.author.getUserId())
                .excute(new JsonCallBack<JSONObject>() {
                    @Override
                    public void OnSuccess(ApiResponse<JSONObject> response) {
                        if (response.body != null) {
                            boolean hasFollow = response.body.getBoolean("hasLiked");
                                feed.author.setHasFollow(hasFollow);
                                LiveDataBus.get().with(DATA_FROM_INTERACTION)
                                        .postValue(feed);
                        }
                    }

                    @Override
                    public void OnError(ApiResponse<JSONObject> response) {
                        showToast(response.message);
                    }
                });
    }

    public static LiveData<Boolean> deleteFeed(Context context, long itemId) {
        MutableLiveData<Boolean> liveData = new MutableLiveData<>();
        new AlertDialog.Builder(context)
                .setNegativeButton("删除", (dialog, which) -> {
                    dialog.dismiss();
                    deleteFeedInternal(liveData, itemId);
                }).setPositiveButton("取消", (dialog, which) -> dialog.dismiss()).setMessage("确定要删除这条评论吗？").create().show();
        return liveData;
    }

    private static void deleteFeedInternal(MutableLiveData<Boolean> liveData, long itemId) {
        ApiService.get("/feeds/deleteFeed")
                .addParam("itemId", itemId)
                .excute(new JsonCallBack<JSONObject>() {
                    @Override
                    public void OnSuccess(ApiResponse<JSONObject> response) {
                        if (response.body != null) {
                            boolean success = response.body.getBoolean("result");
                                liveData.postValue(success);
                                showToast("删除成功");

                        }
                    }

                    @Override
                    public void OnError(ApiResponse<JSONObject> response) {
                        showToast(response.message);
                    }
                });
    }

    //删除某个帖子的一个评论
    public static LiveData<Boolean> deleteFeedComment(Context context, long itemId, long commentId) {
        MutableLiveData<Boolean> liveData = new MutableLiveData<>();
        new AlertDialog.Builder(context)
                .setNegativeButton("删除", (dialog, which) -> {
                    dialog.dismiss();
                    deleteFeedCommentInternal(liveData, itemId, commentId);
                }).setPositiveButton("取消", (dialog, which) -> dialog.dismiss()).setMessage("确定要删除这条评论吗？").create().show();
        return liveData;
    }

    private static void deleteFeedCommentInternal(LiveData liveData, long itemId, long commentId) {
        ApiService.get("/comment/deleteComment")
                .addParam("userId", QQUserManager.getInstance().getUserId())
                .addParam("commentId", commentId)
                .addParam("itemId", itemId)
                .excute(new JsonCallBack<JSONObject>() {
                    @Override
                    public void OnSuccess(ApiResponse<JSONObject> response) {
                        if (response.body != null) {
                            boolean result = response.body.getBoolean("result");
                                ((MutableLiveData) liveData).postValue(result);
                                showToast("评论删除成功");

                        }
                    }

                    @Override
                    public void OnError(ApiResponse<JSONObject> response) {
                        showToast(response.message);
                    }
                });
    }


    //关注/取消关注一个帖子标签
    public static void toggleTagLike(LifecycleOwner owner, TagList tagList) {
        if (!QQUserManager.getInstance().isLogin()) {
            LiveData<User> loginLv = QQUserManager.getInstance().login(MyApplication.getsApplication());
            loginLv.observe(owner, new Observer<User>() {
                @Override
                public void onChanged(User user) {
                    if (user != null) {
                        toggleTagLikeInternal(tagList);
                    }
                    loginLv.removeObserver(this);
                }
            });
        }else {
            toggleTagLikeInternal(tagList);
        }
    }

    private static void toggleTagLikeInternal(TagList tagList) {
        ApiService.get("/tag/toggleTagFollow")
                .addParam("tagId", tagList.tagId)
                .addParam("userId", QQUserManager.getInstance().getUserId())
                .excute(new JsonCallBack<JSONObject>() {
                    @Override
                    public void OnSuccess(ApiResponse<JSONObject> response) {
                        if (response.body != null) {
                            Boolean follow = response.body.getBoolean("hasFollow");
                                tagList.setHasFollow(follow);

                        }
                    }

                    @Override
                    public void OnError(ApiResponse<JSONObject> response) {
                        showToast(response.message);
                    }
                });
    }
} 
